package com.example.demo2.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo2.common.Result;
import com.example.demo2.entity.Customer;
import com.example.demo2.entity.DTO.CustomerDTO;
import com.example.demo2.exception.ServiceException;
import com.example.demo2.mapper.CustomerMapper;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

@Service
public class CustomerService extends ServiceImpl<CustomerMapper, Customer> {
    public Result saveOrUpdateCustomer(Customer customer) {
        LambdaQueryWrapper<Customer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Customer::getUsername, customer.getUsername());
        Customer one = getOne(lqw);
        if (one == null) {
            return Result.success(saveOrUpdate(customer));
        } else {
            throw new ServiceException("-1","该用户名太受欢迎了，请更换一个");
        }
    }

    public Result removeByIdOfCustomer(Integer customerId) {
        boolean removeResult = removeById(customerId);
        if(removeResult){
            return Result.success("","删除成功",removeResult);
        }else {
            return Result.error("-1","删除失败");
        }
    }

    public IPage<Customer> findPageOfCustomer(CustomerDTO customerDTO) {
        LambdaQueryWrapper<Customer> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(customerDTO.getUsername()),Customer::getUsername,customerDTO.getUsername());
        lqw.like(Strings.isNotEmpty(customerDTO.getNickname()),Customer::getNickname,customerDTO.getNickname());
        lqw.like(Strings.isNotEmpty(customerDTO.getSex()),Customer::getSex,customerDTO.getSex());
        lqw.like(Strings.isNotEmpty(customerDTO.getPhone()),Customer::getPhone,customerDTO.getPhone());
        Page<Customer> iPage = new Page<>(customerDTO.getPage(), customerDTO.getLimit());
        return page(iPage,lqw);
    }
}
